var  gravity = new cc.math.Vec2(0.0, -980.0);
var scene ;

var HelloWorldLayer = cc.Layer.extend({
    ball1Mask : 1 << 0,
    wallMask : 1 << 2,
    ropeMask : 1 << 3,
    physicsWorld : null,
    actionBody : null,
    drawTraceLayer : null,
    bounce : 10.0,
    currentV : new cc.math.Vec2(0, 0),
    ballRadius : 10,
    status : 1,
    ballsposition : new cc.math.Vec2(10, 10),
    ctor:function () {
        //////////////////////////////
        // 1. super init first
        this._super();

        /////////////////////////////
        // 2. add a menu item with "X" image, which is clicked to quit the program
        //    you may modify it.
        // ask the window size
        // var size = cc.winSize;
        
        return true;
    },
    init : function() {
        //////////////////////////////
        // 1. super init first
        if ( !this._super() )
        {
            return false;
        }
        
        //显示物理世界调试状态, 显示红色的框, 方便调试
        physicsWorld = scene.getPhysicsWorld();
        physicsWorld.setDebugDrawMask( cc.PhysicsWorld.DEBUGDRAW_ALL);
        physicsWorld.setGravity(gravity);

        Size winsize = Director::getInstance().getWinSize();
        auto visibleSize = Director::getInstance().getVisibleSize();
        Vec2 origin = Director::getInstance().getVisibleOrigin();
        Vec2 s_centre = Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y);
        CCLOG("winsize=(%f,%f) vsize =(%f,%f), o = (%f,%f)",
              winsize.width, winsize.height,
              visibleSize.width, visibleSize.height, origin.x, origin.y);
        
        
        //轨迹层
        drawTraceLayer = DrawTraceLayer::create();
        this.addChild(drawTraceLayer);
        
        //触摸事件
        auto listener1 = EventListenerTouchOneByOne::create();
        // trigger when you push down
        listener1.onTouchBegan = [=](Touch* touch, Event* event){
            if (status == 1 ){
                auto liv_pos = touch.getLocationInView();
                liv_pos = Director::getInstance().convertToUI(liv_pos);
                CCLOG("touch began %f,%f", liv_pos.x, liv_pos.y);
                float dist = liv_pos.distance(ballsposition);
                if (dist <= ballRadius) {
                    status = 2;
                    CCLOG("进入状态2，拉球中");
                }
            }
            return true; // if you are consuming it
        };
        listener1.onTouchMoved = [=](Touch* touch, Event* event) {
            if (status == 2){ //拉球并画轨迹
                auto tp = touch.getLocationInView();
                tp = Director::getInstance().convertToUI(tp);
                actionBody.getNode().setPosition(tp);
                Vec2 dis = tp - ballsposition;
                //垂直向上为0，正时针方向的角度
                float angle = Vec2(dis.y, dis.x).getAngle();
                //sp.setRotation( / 3.14f * 180);
                float dist = tp.getDistance(ballsposition);
                float lx = sin(angle)*dist; //lx = fabs(lx);
                float ly = cos(angle)*dist; //ly = fabs(ly);
                //CCLOG("%f,%f", lx, ly);
                //why ?????
                currentV.y = -ly;
                currentV.x = -lx;
                drawTraceLayer.refreshTraceView(tp, ballsposition, currentV, gravity, bounce);
            }
        };
        listener1.onTouchEnded =[=](Touch* touch, Event* event) {
            if (status == 2) {
                status = -1;
                actionBody.setDynamic(true);
                actionBody.setVelocity(currentV*bounce);
                //drawTraceLayer.clearTrace();
          
            }else {
                status = 1;
            }

        };
        listener1.onTouchCancelled=[=](Touch* touch, Event* event) {
            status = 1;
            actionBody.getNode().setPosition(ballsposition);
            drawTraceLayer.clearTrace();
        };
        
        // Add listener
        _eventDispatcher.addEventListenerWithSceneGraphPriority(listener1, this);
        //END 触摸事件
        
        //创建边界
        auto edgeSp = Sprite::create();//创建一个精灵
        //auto boundBody = PhysicsBody::createEdgeBox(visibleSize,PhysicsMaterial(0.0f,1.0f,0.0f),3);//edgebox是不受刚体碰撞影响的一种刚体，我们用它来设置物理世界的边界
        //创建一个物理世界, 大小和屏幕的尺寸相同, 使用默认材质, debug框的宽度为3个像素 PHYSICSBODY_MATERIAL_DEFAULT
        auto boundBody = PhysicsBody::createEdgeBox( visibleSize, PHYSICSBODY_MATERIAL_DEFAULT , 1);
        boundBody.setMass(wallMask);
        edgeSp.setPosition(s_centre);//位置设置在屏幕中央
        edgeSp.setPhysicsBody(boundBody);//将精灵容纳的刚体设置为boundbody。注意这里不能确定刚体和精灵是不是父子节点的关系。有兴趣的朋友请自行研究。
        addChild(edgeSp);//加入渲染树
        edgeSp.setTag(0);

        //篮筐
        float dt_basketryW = 50;
        float dt_basketryH = s_centre.y;
        //右边篮筐
        auto physicsBody = PhysicsBody::createCircle(40/2, PhysicsMaterial(1.0f, 1.0f, 1.0f));
        boundBody.setCategoryBitmask(wallMask);
        boundBody.setCollisionBitmask(wallMask | ball1Mask);
        boundBody.setContactTestBitmask(wallMask|ball1Mask);
        physicsBody.setDynamic(false);
        auto sprite = Sprite::create("CloseNormal.png");
        sprite.setPosition(Vec2(visibleSize.width - dt_basketryW, dt_basketryH));
        addChild(sprite);
        //apply physicsBody to the sprite
        sprite.setPhysicsBody(physicsBody);
        sprite.setScale(0.2f);
        sprite.setTag(20);
        
        //添加篮球
        //this.actionBody = PhysicsBody::createBox(Size(10.0f, 10.0f), PhysicsMaterial(0.1f, 1.0f, 0.0f));
        this.actionBody = PhysicsBody::createCircle( ballRadius, PhysicsMaterial(1.0f, 1.0f, 1.0f));
        //actionBody.setRotationEnable(false);
        actionBody.setDynamic(false);
        actionBody.setGravityEnable(true);
        actionBody.setCategoryBitmask(ball1Mask);
        actionBody.setCollisionBitmask(wallMask | ball1Mask);
        actionBody.setContactTestBitmask(wallMask|ball1Mask);
        //摩擦力
        actionBody.getFirstShape().setFriction(0.01f);
        //set initial velocity of physicsBody
        //actionBody.setAngularVelocity(av);
        sprite = Sprite::create("CloseSelected.png");
        ballsposition =Vec2(s_centre.x - 100, s_centre.y);
        sprite.setPosition(ballsposition);
        sprite.setPhysicsBody(actionBody);
        addChild(sprite);
        //sprite.setRotation(80);
        sprite.setTag(10);
        
        return true;
    }
});

HelloWorldLayer.createScene() = function(){
    //使用物理世界创建场景
    scene = Scene.createWithPhysics();
    scene.addChild(new HelloWorldLayer());
    return  scene;
    
}


